package com.lack.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lack.openApicommon.model.entity.UserInterfaceInfo;
import com.lack.project.common.ErrorCode;
import com.lack.project.exception.BusinessException;
import com.lack.project.mapper.UserInterfaceInfoMapper;
import com.lack.project.service.UserInterfaceInfoService;
import org.springframework.stereotype.Service;

/**
 * @author qings
 * @description 针对表【user_interface_info(用户接口关系表)】的数据库操作Service实现
 * @createDate 2024-08-26 16:07:03
 */
@Service
public class UserInterfaceInfoServiceImpl extends ServiceImpl<UserInterfaceInfoMapper, UserInterfaceInfo>
        implements UserInterfaceInfoService {


    @Override
    public void validUserInterfaceInfo(UserInterfaceInfo userInterfaceInfo, boolean add) {
        Long userId = userInterfaceInfo.getUserId();
        Long interfaceInfoId = userInterfaceInfo.getInterFaceInfoId();
        Integer totalNum = userInterfaceInfo.getTotalNum();
        Integer leftNum = userInterfaceInfo.getLeftNum();
        if (userId == null || interfaceInfoId == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户id或接口id不能为空");
        }
        if (leftNum < 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "剩余调用次数不能小于0");
        }
    }

    /**
     * 调用次数
     * interfaceinfoId
     *
     * @param userId
     * @return
     */
    @Override
    public boolean invokeCount(long interFaceInfoId, long userId) {
        // 数据校验
        if (interFaceInfoId <= 0 && userId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "数据错误");
        }
        // 更新数据库
        UpdateWrapper<UserInterfaceInfo> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("interFaceInfoId", interFaceInfoId);
        updateWrapper.eq("userId", userId);
        // 剩余调用次数减一，总调用次数加一
        updateWrapper.setSql("leftNum = leftNum - 1 , totalNum=totalNum + 1");
        boolean update = this.update(updateWrapper);
        return update;
    }

    @Override
    public UserInterfaceInfo getUserInterfaceInfo(long interfaceInfoId, long userId) {
        // 数据校验
        if (interfaceInfoId <= 0 && userId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "数据错误");
        }
        QueryWrapper<UserInterfaceInfo> userInterfaceInfoQueryWrapper = new QueryWrapper<>();
        userInterfaceInfoQueryWrapper.eq("interFaceInfoId", interfaceInfoId);
        userInterfaceInfoQueryWrapper.eq("userId", userId);
        return this.getOne(userInterfaceInfoQueryWrapper);
    }
}




